package com.share.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.dao.UserDao;
import com.share.model.User;
import com.share.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private RedisTemplate<String, Object> redis;

    @Override
    public User isExists(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return getOne(queryWrapper);
    }

    @Override
    public void addUser(User user) {
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        save(user);
    }

    @Override
    public void updateUser(User user) {
        updateById(user);
    }

    @Override
    public User getUserById(Long user_id) {
        // 1. 先去 redis中找 users
        if (redis.hasKey("users:" + user_id)) {
            log.info("redis中有数据");
            return (User) redis.opsForValue().get("users:" + user_id);
        }

        // 2. redis中没找到去 MySQL查并放入 redis
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(user_id != null, "user_id", user_id);       // 条件为真时执行查询  否则不查询
        User user = getOne(queryWrapper);
        redis.opsForValue().set("users:" + user_id, user, 1, TimeUnit.DAYS);      // 放入 redis
        log.info("数据放入 redis");
        return user;
    }

    @Override
    public User getUserByPhone(String phone) {
        // 1. 先去 redis中找 users
//        if (redis.hasKey("users:" + phone)) {
//            log.info("redis中有数据");
//            return (User) redis.opsForValue().get("users:" + phone);
//        }

        // 2. redis中没找到去 MySQL查并放入 redis
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(phone != null, "phone", phone);       // 条件为真时执行查询  否则不查询
        //        redis.opsForValue().set("users:" + phone, user, 1, TimeUnit.DAYS);      // 放入 redis
//        log.info("数据放入 redis");
        return getOne(queryWrapper);
    }

    @Override
    public void setTokenToRedis(Long user_id, String token) {
        redis.opsForValue().set("tokens:" + user_id, token);
    }

    @Override
    public void removeTokenFromRedis(Long user_id) {
        redis.delete("tokens:" + user_id);
    }

}
